package com.zut.edu.fragment;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.qmuiteam.qmui.layout.QMUIFrameLayout;
import com.qmuiteam.qmui.layout.QMUILayoutHelper;
import com.qmuiteam.qmui.layout.QMUILinearLayout;
import com.qmuiteam.qmui.recyclerView.QMUIRVItemSwipeAction;
import com.qmuiteam.qmui.recyclerView.QMUISwipeAction;
import com.qmuiteam.qmui.recyclerView.QMUISwipeViewHolder;
import com.qmuiteam.qmui.skin.QMUISkinHelper;
import com.qmuiteam.qmui.skin.QMUISkinManager;
import com.qmuiteam.qmui.skin.QMUISkinValueBuilder;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.util.QMUIResHelper;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.qmuiteam.qmui.widget.popup.QMUIFullScreenPopup;
import com.qmuiteam.qmui.widget.popup.QMUIPopups;
import com.qmuiteam.qmui.widget.pullLayout.QMUIPullLayout;
import com.zut.edu.R;
import com.zut.edu.bean.Event;
import com.zut.edu.bean.Page;
import com.zut.edu.bean.Tag;
import com.zut.edu.http.BaseCallback;
import com.zut.edu.http.OkhttpHelper;
import com.zut.edu.utils.StringUtils;
import com.zut.edu.widget.RotateTextView;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;

public class QueryTagFirstFragment extends Fragment {

    private int currPage = 1;
    private int pageNum = 1;
    private Adapter mAdapter;
    @BindView(R.id.pull_layout)
    QMUIPullLayout mPullLayout;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    private String companyId;
    private String companyName;
    private String url;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_queryrecordfirst, container, false);
        ButterKnife.bind(this,view);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        companyId = StringUtils.getLocalitem(getContext(),"user","companyId");
        companyName = StringUtils.getLocalitem(getContext(),"company","companyName");
        url = "http://39.107.42.126:8088/tag/query";
        initData();

    }


    private void initData() {

        mPullLayout.setActionListener(new QMUIPullLayout.ActionListener() {
            @Override
            public void onActionTriggered(@NonNull final QMUIPullLayout.PullAction pullAction) {
                mPullLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (pullAction.getPullEdge() == QMUIPullLayout.PULL_EDGE_TOP) {
                            onRefreshData();
                        } else if (pullAction.getPullEdge() == QMUIPullLayout.PULL_EDGE_BOTTOM) {
                            if(currPage<=pageNum)onLoadMore();
                            else{
                                final QMUITipDialog tipDialog = new QMUITipDialog.Builder(getContext())
                                        .setTipWord("已无更多数据")
                                        .create();
                                tipDialog.show();

                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            Thread.sleep( 1000);  //线程休眠1秒执行
                                            tipDialog.dismiss();
                                        } catch (InterruptedException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }).start();


                            }
                        }
                        mPullLayout.finishActionRun(pullAction);
                    }
                }, 1000);
            }
        });

        QMUIRVItemSwipeAction swipeAction = new QMUIRVItemSwipeAction(true, new QMUIRVItemSwipeAction.Callback() {
            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
                mAdapter.remove(viewHolder.getAdapterPosition());
            }

            @Override
            public int getSwipeDirection(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
                return QMUIRVItemSwipeAction.SWIPE_LEFT;
            }

            @Override
            public void onClickAction(QMUIRVItemSwipeAction swipeAction, RecyclerView.ViewHolder selected, QMUISwipeAction action) {
                super.onClickAction(swipeAction, selected, action);

                if(mAdapter.mAction1 == action){
                    mAdapter.remove(selected.getAdapterPosition());
                }
                else if(mAdapter.mAction2 == action){
                    mAdapter.interest(selected.getAdapterPosition());
                    swipeAction.clear();
                }
                else if(mAdapter.mAction4 == action){
                    mAdapter.copy(selected.getAdapterPosition());
                    swipeAction.clear();
                }
                else{
                    swipeAction.clear();
                }
            }
        });
        swipeAction.attachToRecyclerView(mRecyclerView);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()) {
            @Override
            public RecyclerView.LayoutParams generateDefaultLayoutParams() {
                return new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT);
            }
        });

        mAdapter = new Adapter(getContext());
        mRecyclerView.setAdapter(mAdapter);
        onDataLoaded(companyId,"1",0);
    }

    private void onDataLoaded(String userId, String pageNo, final int action) {
        OkhttpHelper okhttpHelper = OkhttpHelper.getInstance();
        Map<String,Object> params = new HashMap<>(2);
        params.put("companyId",userId);
        params.put("pageNo",pageNo);
        okhttpHelper.get(url, params, new BaseCallback<Page<Tag>>() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.e("onDataLoaded_onFailure", String.valueOf(e));
            }

            @Override
            public void onSuccess(@NotNull Call call, @NotNull Response response, Page<Tag> tagPage, int code) throws IOException {
                Log.e("onSuccess", "response.code:"+response.code()+"\nresponse.message:"+response.message()+"\nresult.code:"+code);
        //        Collections.shuffle(eventPage.list);
                switch (action){
                    case 0:
                        pageNum = tagPage.pageNum;
                        mAdapter.setData(tagPage.list);
                        break;
                    case 1:
                        mAdapter.prepend(tagPage.list);
                        break;
                    case 2:
                        mAdapter.append(tagPage.list);
                        break;
                }

            }

            @Override
            public void onError(@NotNull Call call, @NotNull Response response, int code, Exception e) {
                Log.e("onError", "response.code:"+response.code()+"\nresponse.message:"+response.message()+"\nresult.code:"+code);
            }
        });
    }

    private void onRefreshData() {
        onDataLoaded(companyId,"1",1);
        mRecyclerView.scrollToPosition(0);
    }

    private void onLoadMore() {
        currPage = ++currPage;
        onDataLoaded(companyId,String.valueOf(currPage),2);

    }

    class Adapter extends RecyclerView.Adapter<QMUISwipeViewHolder>{

        private List<Tag> mData = new ArrayList<>();

        final QMUISwipeAction mAction1;
        final QMUISwipeAction mAction2;
        final QMUISwipeAction mAction4;

        public Adapter(Context context){
            QMUISwipeAction.ActionBuilder builder = new QMUISwipeAction.ActionBuilder()
                    .textSize(QMUIDisplayHelper.sp2px(context, 14))
                    .textColor(Color.WHITE)
                    .paddingStartEnd(QMUIDisplayHelper.dp2px(getContext(), 14));

            mAction1 = builder
                    .text("删除")
                    .backgroundColor(Color.RED)
                    .icon(ContextCompat.getDrawable(context, R.drawable.icon_quick_action_delete_line))
                    .orientation(QMUISwipeAction.ActionBuilder.VERTICAL)
                    .reverseDrawOrder(false)
                    .build();
            mAction2 = builder
                    .text("特别关注")
                    .backgroundColor(Color.BLUE)
                    .icon(ContextCompat.getDrawable(context, R.drawable.icon_quick_action_share))
                    .orientation(QMUISwipeAction.ActionBuilder.VERTICAL)
                    .reverseDrawOrder(true)
                    .build();
            mAction4 = builder
                    .text("复制")
                    .backgroundColor(Color.GRAY)
                    .icon(ContextCompat.getDrawable(context, R.drawable.icon_quick_action_copy))
                    .orientation(QMUISwipeAction.ActionBuilder.HORIZONTAL)
                    .reverseDrawOrder(true)
                    .build();
        }

        public void setData(@Nullable List<Tag> list) {
            mData.clear();
            if(list != null){
                mData.addAll(list);
            }
            notifyDataSetChanged();
        }

        public void remove(int pos){
            mData.remove(pos);
            notifyItemRemoved(pos);
        }

        public void add(int pos, Tag item) {
            mData.add(pos,item);
            notifyItemInserted(pos);
        }

        public void prepend(@NonNull List<Tag> items){
            mData.clear();
            mData.addAll(0, items);
            notifyDataSetChanged();
        }

        public void append(@NonNull List<Tag> items){
            mData.addAll(items);
            notifyDataSetChanged();
        }
        public void copy(int pos){
            String str = mData.get(pos).tagId;
            ClipboardManager cm = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData mClipData = ClipData.newPlainText("Lable", str);
            cm.setPrimaryClip(mClipData);
            Toast.makeText(getContext(), "复制成功",
                    Toast.LENGTH_SHORT).show();
        }

        public void interest(int pos){
            String TagId = mData.get(pos).getTagId();
            OkhttpHelper okhttpHelper = OkhttpHelper.getInstance();
            Map<String,Object> params = new HashMap<>(2);
            params.put("tagId",TagId);
            params.put("tagStatus","3");
            okhttpHelper.post(StringUtils.BASE_URL+"/tag/update", params, new BaseCallback<String>() {
                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) {
                    Log.e("interest_onFailure", String.valueOf(e));
                }

                @Override
                public void onSuccess(@NotNull Call call, @NotNull Response response, String s, int code) throws IOException {
                    Log.e("onSuccess", "response.code:"+response.code()+"\nresponse.message:"+response.message()+"\nresult.code:"+code);
                    Toast.makeText(getContext(), "关注成功", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onError(@NotNull Call call, @NotNull Response response, int code, Exception e) {
                    Log.e("onError", "response.code:"+response.code()+"\nresponse.message:"+response.message()+"\nresult.code:"+code);
                }
            });
        }

        @NonNull
        @Override
        public QMUISwipeViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.simple_list_item_2, parent, false);
            final QMUISwipeViewHolder vh = new QMUISwipeViewHolder(view);
            vh.addSwipeAction(mAction1);
            vh.addSwipeAction(mAction2);
            vh.addSwipeAction(mAction4);
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    QMUISkinValueBuilder builder = QMUISkinValueBuilder.acquire();
                    QMUIFrameLayout frameLayout = new QMUIFrameLayout(getContext());
                    frameLayout.setBackground(
                            QMUIResHelper.getAttrDrawable(getContext(), R.attr.qmui_skin_support_popup_bg));
                    builder.background(R.attr.qmui_skin_support_popup_bg);
                    QMUISkinHelper.setSkinValue(frameLayout, builder);
                    frameLayout.setRadius(QMUIDisplayHelper.dp2px(getContext(), 12));
                    int padding = QMUIDisplayHelper.dp2px(getContext(), 20);
                    frameLayout.setPadding(padding, padding, padding, padding);


                    String tagId = mData.get(vh.getAdapterPosition()).tagId;
                    String tagRange = mData.get(vh.getAdapterPosition()).tagRange;
                    String companyId  = mData.get(vh.getAdapterPosition()).companyId;
                    String tagStatus = mData.get(vh.getAdapterPosition()).tagStatus;
                    tagStatus = StringUtils.statusJudge("tagStatus",tagStatus);


                    TextView textView = new TextView(getContext());
                    textView.setLineSpacing(QMUIDisplayHelper.dp2px(getContext(), 4), 1.0f);
                    textView.setPadding(10, 10, 0, 10);
                    textView.setText("标签编号："+tagId+"\n\n"+"标签范围："+tagRange+"\n\n"+"标签公司："+companyName+"\n\n"+"标签状态："+tagStatus);
                    textView.setTextColor(
                            QMUIResHelper.getAttrColor(getContext(), R.attr.app_skin_common_title_text_color));

                    builder.clear();
                    builder.textColor(R.attr.app_skin_common_title_text_color);
                    QMUISkinHelper.setSkinValue(textView, builder);
                    textView.setGravity(Gravity.CENTER_VERTICAL);

                    builder.release();

                    int size = QMUIDisplayHelper.dp2px(getContext(), 200);
                    FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(size, (int) (size*1.5));
                    frameLayout.addView(textView, lp);

                    QMUIPopups.fullScreenPopup(getContext())
                            .addView(frameLayout)
                            .closeBtn(true)
                            .skinManager(QMUISkinManager.defaultInstance(getContext()))
                            .onBlankClick(new QMUIFullScreenPopup.OnBlankClickListener() {
                                @Override
                                public void onBlankClick(QMUIFullScreenPopup popup) {
                                }
                            })
                            .onDismiss(new PopupWindow.OnDismissListener() {
                                @Override
                                public void onDismiss() {
                                }
                            })
                            .show(v);
                }
            });
            return vh;
        }

        @Override
        public void onBindViewHolder(@NonNull QMUISwipeViewHolder holder, int position) {
            TextView textView1 = holder.itemView.findViewById(R.id.text1);
            TextView textView2 = holder.itemView.findViewById(R.id.text2);
            TextView textView3 = holder.itemView.findViewById(R.id.text3);
            RotateTextView rotateTextView = holder.itemView.findViewById(R.id.qrf_rotate);
            QMUILinearLayout qmuiLinearLayout = holder.itemView.findViewById(R.id.list_linear);


            textView1.setText(mData.get(position).tagId);
            textView2.setText(companyName);
            textView3.setText(mData.get(position).tagRange);
            rotateTextView.setText(StringUtils.statusJudge("tagStatus",mData.get(position).tagStatus));
            rotateTextView.setBackgroundTintList(getResources().getColorStateList(StringUtils.colorJudge("tagStatus",mData.get(position).tagStatus)));
            TextView linertext = holder.itemView.findViewById(R.id.list_linear_text);
            linertext.setText(mData.get(position).tagId.subSequence(0,1));

            qmuiLinearLayout.setRadius(QMUILayoutHelper.RADIUS_OF_HALF_VIEW_WIDTH);
            qmuiLinearLayout.setBackgroundColor(getResources().getColor(StringUtils.colorJudge("randomColor", (String) mData.get(position).tagId.subSequence(0,1))));

        }

        @Override
        public int getItemCount() {
            return mData.size();
        }
    }


}
